<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="referrer" content="no-referrer" />
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../lib/layui-v2.5.5/css/layui.css" media="all">
    <link rel="stylesheet" href="../css/public.css" media="all">
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <!--layui.table图片显示不全，需重新定义CSS  -->
    <style type="text/css">
        .layui-table-cell{
            height:auto!important;
            white-space:normal;
        }

    </style>
</head>
<body>

<!-- 更新商品弹出层 -->
<div id="update-user-layer" style="display: none; padding: 20px">
    <form id="update-user-form" class="layui-form layui-form-pane" lay-filter="update-user-form">
        <div class="layui-form-item">
            <label class="layui-form-label">商品名称</label>
            <div class="layui-input-block">
                <input type="text" name="goodsName" id="goodsName" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">单价</label>
            <div class="layui-input-block">
                <input type="text" name="price" id="price" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">描述</label>
            <div class="layui-input-block">
                <input type="text" name="information" id="information" class="layui-input">
            </div>
        </div>

                <input type="hidden" name="img" id="img" class="layui-input">

        <input type="file" name="text" id="inputId" style="display: inline" >
        <input type="button" onclick="uploadImg()" style="display: inline" value="确认图片">



        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="update-user-form-submit">提交</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </form>

</div>

<div class="layuimini-container">
    <div class="layuimini-main">

        <div class="demoTable">
            搜索商品名称：
            <div class="layui-inline">
                <input class="layui-input" name="goodsName" id="demoReload1" autocomplete="off">
            </div>
            <button class="layui-btn" data-type="reload">搜索</button>
        </div>

        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add"> 添加 </button>
            </div>
        </script>

        <table class="layui-hide" id="goods" lay-filter="currentTableFilter"></table>

        <script type="text/html" id="currentTableBar">
            <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="edit">编辑</a>
            <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">删除</a>
        </script>

    </div>
</div>
<script src="../lib/layui-v2.5.5/layui.js" charset="utf-8"></script>
<script type="text/html" id="imgtmp">
<img src="{{d.img}}">
</script>
<script>
    layui.use(['form', 'table'], function () {
        var $ = layui.jquery,
            form = layui.form,
            goods = layui.table;

        goods.render({
            elem: '#goods',
            url:'/goods/getAllgoods',
            toolbar: '#toolbarDemo',
            title:'商品信息',
            defaultToolbar: ['filter', 'exports', 'print', {
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips'
            }],
            cols: [[
                {field: 'goodsId', width: 120, title: '商品ID'},
                {field: 'goodsName', width: 120, title: '商品名称'},
                {field: 'price', width: 120, title: '单价'},
                {field: 'information', title: '描述', width: 120},
                {field: 'img', width: 240, title: '图片',templet:"#imgtmp"},
                {title: '操作', minWidth: 150, toolbar: '#currentTableBar', align: "center"}
            ]],
            id: 'testReload',
        });
        var $ = layui.$, active = {
            reload: function() {

                var demoReload1 = $('#demoReload1');

                goods.reload('testReload', {
                    url: '/goods/getByGoods_name',
                    where: {
                        goods_name: demoReload1.val()
                    }
                }, 'data');

            }
        };

        $('.demoTable .layui-btn').on('click', function(){
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });

        /**
         * toolbar监听事件
         */
        goods.on('toolbar(currentTableFilter)', function (obj) {
            if (obj.event === 'add') {  // 监听添加操作
                var index = layer.open({
                    title: '添加商品',
                    type: 2,
                    shade: 0.2,
                    maxmin:true,
                    shadeClose: true,
                    area: ['100%', '100%'],
                    content: '../page/table/addgoods.html',
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
            }
        });

        //监听表格复选框选择
        goods.on('checkbox(currentTableFilter)', function (obj) {
            console.log(obj)
        });

        goods.on('tool(currentTableFilter)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') {
                //每次显示更新商品的表单前自动为表单填写该行的数据
                form.val('update-user-form', {
                    "goodsId": data.goodsId,
                    "goodsName": data.goodsName,
                    "price":data.price,
                    "information":data.information,
                });

                // 显示更新商品表单的弹出层
                layer.open({
                    type: 1,
                    title: '编辑商品',
                    skin: 'layui-layer-molv',
                    area: ['500px'],
                    content: $('#update-user-layer')
                });
                // 更新商品表单提交
                form.on('submit(update-user-form-submit)', function(data) {
                    var param=data.field;//定义临时变量获取表单提交过来的数据，非json格式
                    console.log(param);//测试是否获取到表单数据，调试模式下在页面控制台查看


                    // ajax方式更新商品
                    $.ajax({
                        url: "/goods/modifyGoods",
                        type:"PUT",
                        data: JSON.stringify(data.field),
                        contentType: 'application/json;charset=utf-8',
                        dataType: 'json',
                        success: function(data) {
                            if (data.status == 1) {
                                layer.close(layer.index);
                                layer.closeAll();
                                layer.msg('更新成功');
                                goods.reload('testReload');
                            } else {
                                layer.msg('更新失败');
                            }
                        },
                        error: function() {
                            console.log("ajax error");
                        }
                    });
                    // 阻止表单跳转
                    return false;
                });

            } else if (obj.event === 'delete') {
                layer.confirm('确定删除该商品吗', function (index) {
                    $.ajax({
                        url:"/goods/deleteByGoods_id",
                        data:{"goods_id":data.goodsId},
                        success:function (data) {
                            if(data.status==1){
                                layer.msg("删除成功");
                                obj.del();
                            }else {
                                layer.msg("删除失败");
                            }

                        }
                    })
                    layer.close(index);
                });
            }
        });

    });

    function uploadImg(){

        /**
         * formData在jquey中使用需要设置：
         * processData: false, // 告诉jQuery不要去处理发送的数据
         * contentType: false // 告诉jQuery不要去设置Content-Type请求头
         * @type {null}
         */
        var fd = new FormData();

        // 第一个参数为controller 接收的参数名称 , input的id
        fd.append("file", document.getElementById("inputId").files[0]);
        $.ajax({
            url:"/goods/uploadImg",
            type:"post",
            data:fd,
            processData:false,
            contentType:false,
            success:function(res){
                console.log(res.url);

                document.getElementById("img").value=res.url;
                layer.msg("图片上传成功")

                if (res.status == 1) {
                    if (!$('#img').empty()) {
                        $('#img').empty();
                    }
                    // 这一串代码复制不上来 ,截图在下面
                    $('#img').append(" ![](+res.result[0]+)");
                } else {
                    alert("图片上传失败");
                }
            },
            dataType:"json"
        })
    }




</script>

</body>
</html>